package com.vieewer.btdemo.utils;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.provider.ContactsContract;

public class ContactUtils {

    /**
     * 通过电话号码获取姓名
     */
    public String getContactNameFromPhoneNum(Context context, String phoneNum) {
        String contactName = "stranger";
        {
            if (phoneNum != null){
                phoneNum.trim();
            }
            // 处理电话号码格式问题
            ContentResolver cr = context.getContentResolver();
            Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
            while (pCur.moveToNext()) {
                String s = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                s = remove(s, ' ');
                if (s.contains(phoneNum) || phoneNum.contains(s)) {
                    contactName = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                    break;
                }
            }
            pCur.close();
        }
        return contactName;
    }


    // 去掉空格
    public String remove(String resource, char ch) {
        StringBuffer buffer = new StringBuffer();
        int position = 0;
        char currentChar;
        while (position < resource.length()) {
            currentChar = resource.charAt(position++);
            if (currentChar != ch)
                buffer.append(currentChar);
        }
        return buffer.toString();
    }











}
